package com.taotao.sso.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbUserMapper;
import com.taotao.pojo.TbUser;
import com.taotao.pojo.TbUserExample;
import com.taotao.pojo.TbUserExample.Criteria;
import com.taotao.sso.dao.JedisClient;
import com.taotao.sso.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private TbUserMapper userMapper;
	@Autowired
	private JedisClient jedisClient;
	//检查数据是否合法的缓存
	@Value("${REDIS_USER_CHECK_DATA_KEY}")
	private String REDIS_USER_CHECK_DATA_KEY;
	//用户session
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;
	//用户登陆过期时间
	@Value("${SSO_SESSION_EXPIRE}")
	private Integer SSO_SESSION_EXPIRE;
	
	@SuppressWarnings("finally")
	@Override
	public TaotaoResult checkData(String param, Integer type) {
		String redisKey=param+":"+type;
		try {
			String hget = jedisClient.hget(REDIS_USER_CHECK_DATA_KEY, redisKey);
			if(!StringUtils.isBlank(hget)) {
				return TaotaoResult.ok(false);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		
		TbUserExample example=new TbUserExample();
		Criteria criteria = example.createCriteria();
		if(type==1) {
			criteria.andUsernameEqualTo(param);
		}
		else if(type==2) {
			criteria.andEmailEqualTo(param);
		}
		else if(type==3) {
			criteria.andPhoneEqualTo(param);
		}
		List<TbUser> list = userMapper.selectByExample(example);
		
		if(list==null || list.isEmpty())
			return TaotaoResult.ok(true);
		
		//添加缓存
		try {
			jedisClient.hset(REDIS_USER_CHECK_DATA_KEY, redisKey, "true");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			return TaotaoResult.ok(false);
		}
		
		
	}
	
	@Override
	public TaotaoResult insertUser(TbUser user) {
		Date date = new Date();
		user.setCreated(date);
		user.setUpdated(date);
		
		int insert = userMapper.insert(user);
		
		if(insert>0) {
			return TaotaoResult.ok();
		}
		return TaotaoResult.build(400, "注册失败. 请校验数据后请再提交数据.");
		
	}

	
	@Override
	public TaotaoResult userLogin(HttpServletRequest request, HttpServletResponse response,String username, String password) {
		
		TbUserExample example=new TbUserExample();
		example.createCriteria().andUsernameEqualTo(username);
		List<TbUser> userList = userMapper.selectByExample(example);
		if(userList==null || userList.isEmpty()) {
			return TaotaoResult.build(400, "用户: "+username+"不存在");
		}
		TbUser user = userList.get(0);
		if(!user.getPassword().equals(password)) {
			return TaotaoResult.build(400, "密码错误");
		}
		
		user.setPassword(null);
		
		String token=UUID.randomUUID().toString();
		
		jedisClient.set(REDIS_USER_SESSION_KEY+":"+token, JsonUtils.objectToJson(user));
		jedisClient.expire(REDIS_USER_SESSION_KEY+":"+token, SSO_SESSION_EXPIRE);
		CookieUtils.setCookie(request, response, "TT_TOKEN", token,24*60*60*3);

		return TaotaoResult.ok(token);
	}

	
	@Override
	public TaotaoResult getUserByToken(String token) {
		String json = jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);
		if(StringUtils.isBlank(json)) {
			return TaotaoResult.build(400, "用户验证身份已过期，请重新登陆");
		}
		
		return TaotaoResult.ok(JsonUtils.jsonToPojo(json, TbUser.class));
	}

	
	@Override
	public TaotaoResult userLogout(HttpServletRequest request,HttpServletResponse response,String token) {
		String json = jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);
		if(StringUtils.isBlank(json)) {
			return TaotaoResult.build(200, "用户还未登录");
		}
		try {
			jedisClient.del(REDIS_USER_SESSION_KEY+":"+token);
			CookieUtils.deleteCookie(request, response, "TT_TOKEN");
		}
		catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500, "安全退出失败");
		}
		return TaotaoResult.ok();
	}


	
}
